package com.xjoyt.pay.master.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.persistence.Query;
import javax.persistence.criteria.Predicate;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import com.xjoyt.pay.abstracts.AbstractDao;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.master.dao.CompanyProfitRepositoryCustom;
import com.xjoyt.pay.master.params.CompanyProfitGroupParam;
import com.xjoyt.pay.master.params.CompanyProfitPageParam;
import com.xjoyt.pay.master.po.CompanyProfit;
import com.xjoyt.pay.master.repository.CompanyProfitRepository;

public class CompanyProfitRepositoryImpl extends AbstractDao implements CompanyProfitRepositoryCustom {

	@Autowired
	private CompanyProfitRepository repository;

	@Override
	public CompanyProfit findOneByOrderIdAndCompanyId(String orderId, String companyId) {
		Page<CompanyProfit> page = repository.findAllByOrderIdAndCompanyId(orderId, companyId, getFirstPageable());
		return page.hasContent() ? page.iterator().next() : null;
	}

	@Override
	public PageResult<CompanyProfit> loadPage(PageParam<CompanyProfitPageParam> param) {
		Pageable pageable = getPageable(param);
		Specification<CompanyProfit> spec = getSpecification(param.query);
		Page<CompanyProfit> pageReuslt = repository.findAll(spec, pageable);
		return new PageResult<>(pageReuslt.getTotalElements(), pageReuslt.getContent());
	}

	private Specification<CompanyProfit> getSpecification(CompanyProfitPageParam param) {
		Specification<CompanyProfit> spec = (root, query, cb) -> {
			if (param == null) {
				return null;
			}
			List<Predicate> list = new ArrayList<>();
			if (StringUtils.isNotBlank(param.parentId)) {
				list.add(cb.like(root.get("company").get("path"), "%" + param.parentId + "%"));
			}
			if (StringUtils.isNotBlank(param.path)) {
				list.add(cb.or(cb.equal(root.get("company").get("id"), param.path),
						cb.like(root.get("company").get("path"), "%" + param.path + "%")));
			}

			if (StringUtils.isNotBlank(param.companyId)) {
				list.add(cb.equal(root.get("company").get("id"), param.companyId));
			}

			if (param.startDate != null && param.endDate != null) {
				param.startDate = toStartDate(param.startDate);
				param.endDate = toEndDate(param.endDate);
				list.add(cb.between(root.get("addedDate"), param.startDate, param.endDate));
			}

			if (StringUtils.isNotBlank(param.query)) {

				for (String string : param.query.split(" ")) {
					if (StringUtils.isBlank(string))
						continue;
					String like = "%" + string + "%";
					list.add(cb.or(cb.like(root.get("order").get("no"), like)));
				}
			}

			if (CollectionUtils.isNotEmpty(list))
				query.where(cb.and(list.toArray(new Predicate[list.size()])));

			return null;
		};

		return spec;
	}

	@Override
	public List<Map<String, Object>> sum(List<String> companyIds, CompanyProfitGroupParam param) {
		StringBuilder builder = new StringBuilder(
				" select new map(a.company.id as id, sum(a.money) as moneySum, sum( ((a.rate * a.money + a.limit + a.minimum) - (a.costRate * a.money + a.costLimit + a.costMinimum)) + (a.poundage - a.costPoundage) ) as profitSum) from CompanyProfit a where a.company.id in :ids ");
		Map<String, Object> params = new HashMap<>();
		params.put("ids", companyIds);

		if (param.startDate != null && param.endDate != null) {
			param.startDate = toStartDate(param.startDate);
			param.endDate = toEndDate(param.endDate);
			builder.append(" and ( a.addedDate between :startDate and :endDate ) ");
			params.put("startDate", param.startDate);
			params.put("endDate", param.endDate);
		}

		builder.append(" group by a.company.id ");
		Query query = entityManager.createQuery(builder.toString());
		for (Entry<String, Object> entry : params.entrySet()) {
			query.setParameter(entry.getKey(), entry.getValue());
		}

		@SuppressWarnings("unchecked")
		List<Map<String, Object>> result = query.getResultList();
		return result;
	}

	@Override
	public List<Map<String, Object>> profitSum(List<String> companyIds, CompanyProfitPageParam param) {
		StringBuilder builder = new StringBuilder(
				" select new map(a.company.id as id, sum(a.money) as moneySum, sum( ((a.rate * a.money + a.limit + a.minimum) - (a.costRate * a.money + a.costLimit + a.costMinimum)) + (a.poundage - a.costPoundage) ) as profitSum) from CompanyProfit a where a.company.id in :ids ");
		Map<String, Object> params = new HashMap<>();
		params.put("ids", companyIds);

		if (param.startDate != null && param.endDate != null) {
			param.startDate = toStartDate(param.startDate);
			param.endDate = toEndDate(param.endDate);
			builder.append(" and ( a.addedDate between :startDate and :endDate ) ");
			params.put("startDate", param.startDate);
			params.put("endDate", param.endDate);
		}

		if (param.query != null) {
			builder.append(" and (a.order.no like '%" + param.query + "%')");
		}

		builder.append(" group by a.company.id ");
		Query query = entityManager.createQuery(builder.toString());
		for (Entry<String, Object> entry : params.entrySet()) {
			query.setParameter(entry.getKey(), entry.getValue());
		}

		@SuppressWarnings("unchecked")
		List<Map<String, Object>> result = query.getResultList();
		return result;
	}
}
